//
//  WorkSummaryDetailViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/22.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "WorkSummaryDetailViewController.h"
#import "WorkSummaryCommentCell.h"

NSString *const WorkSummaryDetailViewControllerInfoParamKey = @"WorkSummaryDetailViewControllerInfoParamKey";

@interface WorkSummaryDetailViewController ()<XUIGroupTableViewDelegate,XUIGroupTableViewDataSource,XUIButtonDelegate,UITextViewDelegate>
{
    WorkSummaryList *_workSummaryList;
    
    NSMutableArray *_qdData;
    XUIGroupTableView *_gtable;
    
    RSWDataOperation *_manager;
    
    XUITextView *_titileTextView;
    XUITextView *_contentTextView;
    
    UITextView *_textInputViewCell;
    
    XUIButton *_delBtn;
    XUIButton *_editBtn;
}
@end

@implementation WorkSummaryDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    [self setBackNavigateItemTitle:@"工作纪要详情"];
   
    [self initVariable];
    [self initUI];
    
    [_manager getWorkSummaryCommentById:_workSummaryList.workSummaryId isView:NO completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [self requestComplete:nil funcationName:@"getWorkSummaryCommentById" result:nResult output:list error:error];
     }];
    
    [self addKeyboardObserver]; 
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [self removeObserver];
    [_manager terminateRequest];
}

- (void)initVariable
{
    _qdData = [NSMutableArray new];
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    _workSummaryList = self.param[WorkSummaryDetailViewControllerInfoParamKey];
}

- (void)initUI
{
    _delBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeLeftHeadImage delegate:self];
    _delBtn.size = CGSizeMake(20, 20);
    [_delBtn SetTitleColor:[UIColor colorWithHex:mcrmSAASUISkinColorTextStyle25B6EDColor]];
    [_delBtn SetFont:[UIFont systemFontOfSize:13]];
    [_delBtn SetImage:[UIImage imageNamed:@"nav_btn_delete"]];
    _delBtn.delegate = self;
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:(UIView*)_delBtn];
    
    _editBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeLeftHeadImage delegate:self];
    _editBtn.size = CGSizeMake(20, 20);
    [_editBtn SetTitleColor:[UIColor colorWithHex:mcrmSAASUISkinColorTextStyle25B6EDColor]];
    [_editBtn SetFont:[UIFont systemFontOfSize:13]];
    [_editBtn SetImage:[UIImage imageNamed:@"nav_btn_submit"]];
    _editBtn.delegate = self;
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithCustomView:(UIView*)_editBtn];

    NSArray *itemArr = [NSArray arrayWithObjects:item2,item1, nil];
    
    self.navigationItem.rightBarButtonItems = [itemArr mutableCopy];
    
    _gtable = [[XUIGroupTableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    _gtable.delegate = self;
    _gtable.dataSource = self;
    
    [self.view addSubview:_gtable];
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                 _qdData = output;
                 
                 [_gtable reloadData];
                 
                 break;
             }
             default:
             {
                 [UIAlertView showErrorMsg:@"数据请求失败"];
                 break;
             }
         }
     }];
}

#pragma mark --
#pragma mark -- groupTableView delegate

- (NSUInteger)numberOfGroupsInGroupTableView:(XUIGroupTableView *)groupTableView
{
    return 2;
}

- (NSUInteger)groupTableView:(XUIGroupTableView *)groupTableView numberOfRowsInGroup:(NSInteger)group
{
    if(group ==0)
        return 2;
    else if(group == 1)
        return _qdData.count;
    
    return 0;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForHeaderInGroup:(NSInteger)group
{
    return 10;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section ==0)
    {
        return 90;
    }
    else if(indexPath.section == 1)
    {
        WorkSummaryCommentInfo * l = _qdData[indexPath.row];
        return [WorkSummaryCommentCell caleHeight:groupTableView.width content:l.commentContent];
    }
    
    return 0;
}

- (XUIGroupTableViewCell *)groupTableView:(XUIGroupTableView *)groupTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [self groupTableView:groupTableView heightForRowAtIndexPath:indexPath];
    if(indexPath.section ==0)
    {
        XUIGroupTableViewCell *cell = [[XUIGroupTableViewCell alloc] initWithFrame:CGRectZero];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
         
        if(indexPath.row == 0)
        {
            NSString *text = @"标题";
            CGSize size = [text stringSizeWithSystemFontSize:13];
            UILabel *_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, size.width, 18)];
            _titleLabel.textColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStyle333333Color];
            _titleLabel.font = [UIFont systemFontOfSize:13];
            _titleLabel.textAlignment = NSTextAlignmentLeft;
            _titleLabel.text = text;
            _titleLabel.textColor = [UIColor grayColor];
            _titleLabel.centerY = height/2;
            [cell addSubview:_titleLabel];
            
            CGFloat width = groupTableView.width - 10 - _titleLabel.width - 5 - 10;
            _titileTextView = [[XUITextView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
            _titileTextView.delegate = self;
            _titileTextView.textInputMaxLength = 50;
            _titileTextView.hiddenDoneButton = NO;
            _titileTextView.text = _workSummaryList.title;
            _titileTextView.font = [UIFont systemFontOfSize:16];
            
            _titileTextView.left = _titleLabel.right + 5;
            
            [cell addSubview:_titileTextView];

        }
        else if(indexPath.row == 1)
        {
            NSString *text = @"内容";
            CGSize size = [text stringSizeWithSystemFontSize:13];
            UILabel *_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, size.width, 18)];
            _titleLabel.textColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStyle333333Color];
            _titleLabel.font = [UIFont systemFontOfSize:13];
            _titleLabel.textAlignment = NSTextAlignmentLeft;
            _titleLabel.text = text;
            _titleLabel.textColor = [UIColor grayColor];
            _titleLabel.centerY = height/2;
            
            [cell addSubview:_titleLabel];
            
            CGFloat width = groupTableView.width - 10 - _titleLabel.width - 5 - 10;
            _contentTextView = [[XUITextView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
            _contentTextView.delegate = self;
            _contentTextView.textInputMaxLength = 500;
            _contentTextView.hiddenDoneButton = NO;
            _contentTextView.text = _workSummaryList.content;
            _contentTextView.font = [UIFont systemFontOfSize:16];
            
            _contentTextView.left = _titleLabel.right + 5;
            
            [cell addSubview:_contentTextView];
        }
       
        return cell;
    }
    else if(indexPath.section == 1)
    {
        WorkSummaryCommentInfo * l = _qdData[indexPath.row];
        
        WorkSummaryCommentCell *cell = [[WorkSummaryCommentCell alloc] initWithFrame:CGRectMake(0, 0, groupTableView.width, height)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.createUser = l.createUser;
        cell.createTime = [l.createTime toStringDate:NSDateFormatByyMdHm];
        cell.commentContent = l.commentContent;
        
        return cell;
    }
    
    return nil;
}


#pragma mark --
#pragma mark -- keyBoard
- (BOOL)keyboardDidShow:(NSNotification *)noti
{
    BOOL bResult = [super keyboardDidShow:noti];
    if (YES == bResult)
    {
        _gtable.height -= self.keyboardOffSet;
        
        if (_textInputViewCell != nil)
        {
            [_gtable scrollRectToVisible:_textInputViewCell.frame animated:YES];
        }
    }
    return bResult;
}

-(BOOL)keyboardWillHide:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillHide:noti];
    if(YES == bResult)
    {
        _gtable.height += self.keyboardOffSet;
    }
    return bResult;
}

-(void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    _gtable.height += changeSize;
}

#pragma mark --
#pragma mark -- UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    _textInputViewCell = textView;
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    _textInputViewCell = nil;
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    [UIViewController closeKeyBoard];
    
    if(btn == _editBtn)
    {
        if([self submit] == NO)
            return;
        
        [XUIAlertView alertViewWithTitle:@"提示" message:@"是否更新该笔记" cancelButtonTitle:@"更新" otherButtonTitles:@[@"取消"] clickBlock:^(NSInteger nClickindex)
         {
             if(nClickindex == 0)
             {
                 [self modifyRecord];
             }
         }];
    }
    else if(btn == _delBtn)
    {
        [XUIAlertView alertViewWithTitle:@"提示" message:@"是否删除该笔记" cancelButtonTitle:@"删除" otherButtonTitles:@[@"取消"] clickBlock:^(NSInteger nClickindex)
         {
             if(nClickindex == 0)
             {
                 [self delRecord];
             }
         }];
    }
}

-(BOOL)submit
{
    if(_titileTextView.text.length <= 0)
    {
        [UIAlertView showInfoMsg:@"标题不能为空"];
        return NO;
    }
    
    if(_contentTextView.text.length <= 0)
    {
        [UIAlertView showInfoMsg:@"内容不能为空"];
        return NO;
    }
    
    return YES;
}

- (void)modifyRecord
{
    WorkSummaryInfo *modelInfo = [WorkSummaryInfo emptyWorkSummaryInfo];
    modelInfo.workSummaryId = _workSummaryList.workSummaryId;
    modelInfo.title = _titileTextView.text;
    modelInfo.content = _contentTextView.text;
    
    [_manager modifyWorkSummary:modelInfo completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"更新成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"更新失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"更新失败"];
                      break;
                  }
              }
          }];
     }];
}

- (void)delRecord
{
    WorkSummaryInfo *modelInfo = [WorkSummaryInfo emptyWorkSummaryInfo];
    modelInfo.workSummaryId = _workSummaryList.workSummaryId;
    
    [_manager deleteWorkSummary:modelInfo completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"删除成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"删除失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"删除失败"];
                      break;
                  }
              }
          }];
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
